<template>
    <LazyLayoutHeaderM>
        <template #left>
            <img class="left-icon" @click="onShowSearch" :src="`${_oss_}images/mobile/icon-search.png`" />
        </template>

        <TabsGroupM :list="tabsList" v-model:active="tabIndex" @change="onTabsChange" />

        <div class="input-group" v-show="isShowSearch">
            <var-icon name="magnify" color="#999" size="18px" />

            <input ref="searchInputRef" type="text" placeholder="搜索关键字" v-model="keyword" />
            <button @click="onSearch">搜索</button>
        </div>
    </LazyLayoutHeaderM>

    <div class="page">
        <Swiper :modules="[Virtual, Controller]" class="video-swipe" direction="vertical" virtual
            :initial-index="videoSwipeIndex" @slideChange="onVideoSwipeChange" :style="{ height: swiperHeight + 'px' }"
            @swiper="(ref) => (swiperRef = ref)">
            <SwiperSlide class="video-swipe-item" v-for="(item, index) in renderList" :key="item.id" :virtual-index="index">
                <template v-if="Math.abs(videoSwipeIndex - index) <= 2">
                    <div class="item--title">{{ item.name }}</div>

                    <VideoM :data="item" v-model:muted="isMuted" :ref="(el) => setItemRef(el, index)" />

                    <div class="right-box">
                        <div class="avatar">
                            <img :src="item.user.avatar ||
                                `${_oss_}images/user/default-avatar.png`
                                " />
                        </div>

                        <div class="s--icon icon-eye">
                            <img :src="`${_oss_}images/mobile/works/video/icon-eye.svg`" />
                            <div class="s--text">{{ item.page_view }}</div>
                        </div>
                        <div class="s--icon icon-heart" @click="onLike(item)">
                            <img :src="item.is_like
                                    ? `${_oss_}images/mobile/works/video/icon-heart_active.svg`
                                    : `${_oss_}images/mobile/works/video/icon-heart.svg`
                                " />
                            <div class="s--text">{{ item.like }}</div>
                        </div>
                        <div class="s--icon icon-comment" @click="onComment(item)">
                            <img :src="`${_oss_}images/mobile/works/video/icon-comment.svg`" />
                            <div class="s--text">{{ item.comment }}</div>
                        </div>
                        <div class="s--icon icon-star" @click="onStar(item)">
                            <img :src="item.is_star
                                    ? `${_oss_}images/mobile/works/video/icon-star_active.svg`
                                    : `${_oss_}images/mobile/works/video/icon-star.svg`
                                " />
                            <div class="s--text">{{ item.star }}</div>
                        </div>
                        <div class="s--icon icon-share" @click="onShare(item)">
                            <img :src="`${_oss_}images/mobile/works/video/icon-share.svg`" />
                            <div class="s--text">{{ item.share }}</div>
                        </div>
                    </div>

                    <div class="bottom-box">
                        <div class="bottom-box__title">
                            {{ item.user.nickname || item.user.mobile }}

                            <div class="make-same-btn" @click="onMakeSame(item)">
                                <img :src="`${_oss_}images/mobile/works/icon-make.png`" />
                                制作
                            </div>
                        </div>

                        <div class="bottom-box__desc">
                            <template v-if="!!item.introduce">
                                {{
                                    item.introduce.length > introduceLen
                                    ? getHiddenIntroduce(item.introduce)
                                    : item.introduce
                                }}
                                <span class="expand-btn" v-if="item.introduce.length > introduceLen"
                                    @click="onExpand(item)">
                                    展开
                                </span>
                            </template>
                        </div>

                        <div class="exp-btn" @click="onPreview(item)">
                            立即体验
                        </div>
                    </div>
                </template>
            </SwiperSlide>
        </Swiper>
    </div>

    <var-popup position="bottom" :overlay="false" v-model:show="moreShow">
        <div class="introduce-block">
            <div class="introduce-arrow" @click="moreShow = false">
                <img :src="`${_oss_}images/mobile/works/icon-arrow-top.svg`" />
            </div>

            <div class="introduce-top">
                <div class="introduce-top__title">
                    {{ expandItem.user.nickname || expandItem.user.mobile }}
                </div>

                <div class="make-same-btn" @click="onMakeSame(expandItem)">
                    <img :src="`${_oss_}images/mobile/works/icon-make-blue.svg`" />
                    制作
                </div>
            </div>
            <div class="introduce-box">
                {{ expandItem.introduce }}
            </div>
        </div>
    </var-popup>
</template>
<script setup>
import { useContent } from ".";
import { useLike, useStar } from "@/hooks";
import { Dialog } from "@varlet/ui";
import { Virtual, Controller } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/vue";
import {
    SetTaskScore,
    PostWorksShare,
    GetWorksShare,
    GetEditVersion,
} from "~/api";

const pageStore = usePageStore();
const userStore = useUserStore();
const dialogStore = useDialogStore();
const duration = ref(300);
const moreShow = ref(false);
const expandItem = ref({});

const {
    keyword,
    list,
    topList,
    hotList,
    famousList,
    academyList,
    GetNewList,
    GetTopList,
    GetHotList,
    GetFamousList,
    GetAcademyList,
} = useContent();

const swiperHeight = ref(0);

const { onLike } = useLike();
const { onStar } = useStar();
const introduceLen = 31;

const isShowSearch = ref(false);
const videoRef = ref({});
const swiperRef = ref(null);
const searchInputRef = ref(null);
const tabIndex = ref(0);
const videoSwipeIndex = ref(0);
const lastKeyword = ref("");
const isMuted = ref(true);
// const showTips = ref(false);
let dialog = null;

const tabsList = ref([
    {
        label: "推荐",
        value: 0,
        list: computed(() => {
            return topList.value.filter((item) => {
                return (
                    !lastKeyword.value || item.name.includes(lastKeyword.value)
                );
            });
        }),
    },
    {
        label: "院校",
        value: 1,
        list: computed(() => {
            return academyList.value.filter((item) => {
                return (
                    !lastKeyword.value || item.name.includes(lastKeyword.value)
                );
            });
        }),
    },
    {
        label: "名企",
        value: 2,
        list: computed(() => {
            return famousList.value.filter((item) => {
                return (
                    !lastKeyword.value || item.name.includes(lastKeyword.value)
                );
            });
        }),
    },
    {
        label: "热门",
        value: 3,
        list: computed(() => {
            return hotList.value.filter((item) => {
                return (
                    !lastKeyword.value || item.name.includes(lastKeyword.value)
                );
            });
        }),
    },
    {
        label: "最新",
        value: 4,
        list: computed(() => {
            return list.value.filter((item) => {
                return (
                    !lastKeyword.value || item.name.includes(lastKeyword.value)
                );
            });
        }),
    },
]);

const renderList = computed(() => {
    return [
        ...tabsList.value[0].list,
        ...tabsList.value[1].list,
        ...tabsList.value[2].list,
        ...tabsList.value[3].list,
        ...tabsList.value[4].list,
    ];
});

onMounted(async () => {
    swiperHeight.value = window.innerHeight - 44;

    const data = await Promise.all([
        GetNewList(),
        GetTopList(),
        GetHotList(),
        GetFamousList(),
        GetAcademyList(),
    ]);

    list.value = data[0] || [];
    topList.value = data[1] || [];
    hotList.value = data[2] || [];
    famousList.value = data[3] || [];
    academyList.value = data[4] || [];

    if (!pageStore.isVideoError) {
        dialog = Dialog({
            title: "提示",
            message: "当前页面会自动开启视频声音",
            cancelButton: false,
            onClosed() {
                isMuted.value = false;
                dialog = null;
                initVideo(videoSwipeIndex.value);
            },
        });
    }
});

const initVideo = async (index) => {
    await nextTick();

    if (renderList.value.length == 0) return false;

    if (!pageStore.isVideoError) {
        videoRef.value[index].play();
    }
};

const onPreview = (item) => {
    if (userStore.isLogin) {
        SetTaskScore({
            code: 1003,
            _id: item.id,
        });

        window.open(item.url, "_self");
    } else {
        LoginModal(
            true,
            {
                url: item.url,
            },
            {
                code: 1003,
                _id: item.id,
            },
            false
        );
    }
};

const onShare = async (item) => {
    dialogStore.isShareTemplateDialogVisible = true;
    dialogStore.shareUrl = item.url;
    dialogStore.shareName = item.name;

    await SetTaskScore({
        code: 1004,
        _id: item.id,
    });

    await PostWorksShare({
        work_id: item.id,
    });

    const res = await GetWorksShare({ work_id: item.id });
    item.share = res.data;
};

const onExpand = (item) => {
    expandItem.value = item;
    moreShow.value = true;
};

const onComment = async (item) => {
    if (userStore.isLogin) {
        dialogStore.isCommentListDialogVisible = true;
        dialogStore.commentWorkId = item.id;
    } else {
        LoginModal();
    }
};

const getHiddenIntroduce = (introduce) => {
    return introduce.slice(0, introduceLen) + "...";
};

const onMakeSame = async (item) => {
    if (userStore.isLogin) {
        if (pageStore.isMobile) {
            const res = await GetEditVersion();
            if (localStorage.getItem("editor_version") !== res.data) {
                localStorage.setItem("editor_version", res.data);
                dialogStore.isEditorUpdateTipsDialogVisible = true;
            } else {
                Message().warning("请在电脑端网站打开！网址www.ykjhr.com");
            }
        } else {
            const search =
                "tid=" +
                item.templates_id +
                "&type=template&uid=" +
                userStore.userInfo.id;
            const newUrl = `https://medit.ykjhr.com/?${aesEncrypt(search)}`;
            jumpUrl(newUrl);
        }
    } else {
        LoginModal(
            true,
            pageStore.isMobile
                ? {}
                : {
                    url: `https://medit.ykjhr.com/`,
                    search: "tid=" + item.templates_id + "&type=template",
                    params: ["uid"],
                    encrypt: true,
                },
            {},
            !pageStore.isMobile
        );
    }
};

onBeforeUnmount(() => {
    dialog && dialog.close();
});

const onShowSearch = async () => {
    isShowSearch.value = true;
    await nextTick();
    searchInputRef.value.focus();
};

const onVideoSwipeChange = ({ activeIndex }) => {
    if (!pageStore.isVideoError) {
        videoRef.value[videoSwipeIndex.value].pause();
    }

    let lens = tabsList.value.map((item) => item.list.length);

    let sum = 0;
    let i = 0;

    while (i < lens.length) {
        sum += lens[i];
        if (activeIndex < sum) {
            tabIndex.value = i;
            break;
        }
        i++;
    }

    initVideo(activeIndex);
    videoSwipeIndex.value = activeIndex;
};

const setItemRef = (el, index) => {
    videoRef.value[index] = el;
};

const onSearch = async () => {
    if (keyword.value != lastKeyword.value) {
        videoRef.value = {};
        videoSwipeIndex.value = 0;
        tabIndex.value = 0;
        await nextTick();
        setTimeout(() => {
            swiperTo(0);
            lastKeyword.value = keyword.value;
            initVideo(videoSwipeIndex.value);
            isShowSearch.value = false;
        }, 1000);
    } else {
        isShowSearch.value = false;
    }
};

const swiperTo = (index) => {
    swiperRef.value.slideTo(index, 0);
};

const onTabsChange = async (index) => {
    if (index == 0) {
        swiperTo(0);
        return false;
    }

    let lens = tabsList.value.map((item) => item.list.length);

    let num = lens.slice(0, index).reduce((a, b) => a + b);
    swiperTo(num);
};
</script>
<style lang="scss" scoped>
.volume-tips {
    width: 180px;
    height: 39px;

    position: absolute;
    top: 150px;
    left: 50%;
    transform: translateX(-50%);

    background: rgba(0, 0, 0, 0.5);
    border-radius: 4px;
    z-index: 10;

    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
}

.header {
    .left-icon {
        width: 15px;
        height: 15px;
        margin-left: 11px;
    }

    .tab-list {
        position: absolute;
        left: 50%;
        width: 70%;
        transform: translateX(-50%);
        margin: 0;

        :deep(.tab-list__item) {
            padding: 0;
            font-size: 16px;
            flex: 1;

            &.active {
                font-weight: bold;

                &::after {
                    width: 30px;
                    height: 2px;
                    bottom: -5px;
                }
            }
        }

        &::after {
            height: 0px;
        }
    }

    .input-group {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 44px;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;

        .var-icon {
            position: absolute;
            left: 32px;
            font-size: 16px;
        }

        input {
            width: 272px;
            height: 33px;
            border-radius: 17px 0 0 17px;
            background-color: #f1f1f1;
            border: none;
            outline: none;
            padding-left: 30px;
            font-size: 14px;

            &::placeholder {
                font-size: 14px;
            }
        }

        button {
            border: none;
            outline: none;
            width: 59px;
            height: 33px;
            border-radius: 0 17px 17px 0;
            font-weight: 500;
            background-color: #5085fb;
            font-size: 14px;
            color: #ffffff;
        }
    }
}

.video-swipe {
    // height: calc(100vh - 44px);

    :deep(.video-swipe-item) {
        position: relative;
        height: 100%;
        background-color: #000;

        .item--title {
            text-align: center;
            height: 100px;
            text-align: center;
            font-weight: 800;
            font-size: 23px;
            color: #fff;
            padding-top: 25px;
        }

        .video-box {
            width: 100%;
            position: absolute;
            top: 270px;
            left: 0;
            z-index: 1;
            transform: translateY(-50%);
        }

        .right-box {
            position: absolute;
            right: 13px;
            bottom: 15%;
            z-index: 99;
            display: flex;
            flex-direction: column;
            align-items: center;

            .avatar {
                margin-bottom: 15px;

                img {
                    width: 45px;
                    height: 45px;
                    border-radius: 50%;
                    object-fit: cover;
                }
            }

            .s--icon {
                margin-bottom: 15px;

                img {
                    width: 35px;
                }

                .s--text {
                    font-weight: 500;
                    font-size: 14px;
                    color: #ffffff;
                    text-shadow: 0px 1px 1px rgba(0, 0, 0, 0.6);
                    text-align: center;
                }

                .icon-heart {
                    width: auto;
                    height: 29px;
                }
            }
        }

        .bottom-box {
            width: 100%;
            position: absolute;
            left: 0;
            bottom: 0;
            padding-bottom: 20px;
            z-index: 98;

            &__title {
                display: flex;
                align-items: center;
                width: 100%;
                font-weight: 800;
                font-size: 16px;
                color: #fff;
                padding-left: 12px;

                .make-same-btn {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 55px;
                    height: 23px;
                    background: #5185fb;
                    border-radius: 3px;
                    font-weight: 500;
                    font-size: 12px;
                    color: #fff;
                    margin-left: 13px;

                    img {
                        width: 11px;
                        height: 11px;
                        margin-right: 4px;
                    }
                }
            }

            &__desc {
                width: 279px;
                min-height: 20px;
                font-weight: 500;
                font-size: 14px;
                color: #fff;
                line-height: 24px;
                margin: 10px 0;
                padding-left: 12px;

                .expand-btn {
                    font-weight: 800;
                    font-size: 14px;
                    color: #fff;
                }
            }

            .exp-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 350px;
                height: 45px;
                background: #5185fb;
                border-radius: 3px;
                color: #fff;
                font-weight: bold;
                font-size: 17px;
                margin: 0 auto;
            }
        }
    }
}

.introduce-box {
    font-weight: 500;
    font-size: 14px;
    color: #666666;
    line-height: 24px;
    padding: 20px;
    text-align: justify;
    word-wrap: break-word;
    word-break: break-all;
}

.introduce-block {
    width: 100%;
    border-radius: 15px 15px 0 0;
    background-color: #fff;
}

.introduce-arrow {
    width: 16px;
    margin: 0 auto;
    padding: 0 0 10px;
    transform: rotate(180deg);

    img {
        width: 100%;
    }
}

.introduce-top {
    display: flex;
    justify-content: space-between;
    padding: 20px 20px 0;

    &__title {
        font-weight: 800;
        font-size: 16px;
        color: #333333;
    }

    .make-same-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 55px;
        height: 23px;
        background: rgba(80, 133, 251, 0.2);
        border-radius: 3px;
        font-weight: 500;
        font-size: 12px;
        color: #5185fb;

        img {
            width: 11px;
            height: 11px;
            margin-right: 4px;
        }
    }
}
</style>
